#include "myservertest.h"
#include "ui_myservertest.h"

myServerTest::myServerTest(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::myServerTest)
{
    ui->setupUi(this);

    //初始化模型
    m_ModelMain = new QStandardItemModel(this);
    //    m_ModelMain->setColumnCount();
    ui->tabViewMain->setModel(m_ModelMain);
    ui->tabViewMain->setSelectionModel(&m_selectionMain);
    m_selectionMain.setModel(m_ModelMain);

    //初始化成员变量值
    m_serverAddress = "-1";
    m_serverPort = -1;
    m_maxCount = 200;//默认最大线程数量为200
    m_timer1 = NULL;

    m_connectTotalCount = 0;
    m_connectSuccesCount = 0;
    m_connectFalseCount = 0;

    //设置状态栏
    m_statueLabel1.setText(tr("服务器地址:")+"none");
    m_statueLabel2.setText(tr("端口:")+"none");
    m_statueLabel3.setText(tr("活跃连接:")+"none");
    ui->statusbar->addWidget(&m_statueLabel1,1);
    ui->statusbar->addWidget(&m_statueLabel2,1);
    ui->statusbar->addWidget(&m_statueLabel3,1);

}

myServerTest::~myServerTest()
{
    delete ui;
}

void myServerTest::refreshView()
{

}

int myServerTest::currentActiveConnectCount()
{
    int activeCount = 0;
    if(m_progressStatueList.count() != 0){
        for(int i = 0; i < m_progressStatueList.count(); ++i){
            if(m_progressStatueList.at(i) == true){
                ++activeCount;
            }
        }
    }


    return activeCount;
}

void myServerTest::on_actSetServerMain_triggered()
{
    mySercerTestSetting* msts = new mySercerTestSetting;
    int result = msts->exec();
    if(result == QDialog::Accepted){//如果服务器测试连接成功
        m_serverAddress = msts->getServerAddress().simplified();
        m_serverPort = msts->getServerPort();

        //更新状态栏信息
        m_statueLabel1.setText(tr("服务器地址:")+m_serverAddress);
        m_statueLabel2.setText(tr("端口:")+QString::asprintf("%d",m_serverPort));

        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+m_serverAddress+":"+QString::asprintf("%d",m_serverPort)+tr(" 可以正常连接..."));


    }

    msts->myDeleteThis();
    msts->deleteLater();

}


void myServerTest::on_actAppendMain_triggered()
{

    bool ok = false;
    int appendCount = QInputDialog::getInt(0,tr("添加连接"),tr("请输入要添加的连接数量:"),0,0,m_maxCount,10,&ok);
    if(ok == true){//如果输入合理
        if(appendCount == 0){
            return;
        }

        if(appendCount + m_progressList.count() > m_maxCount){//如果即将超过最大允许连接数量
            QMessageBox::warning(0,tr("警告"),tr("已超出最大线程数量!"));
            return;
        }

        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+tr("正在统计数据..."));
        ui->actAppendMain->setEnabled(false);

        m_connectTotalCount = appendCount;//记录用户输入的连接个数
        m_connectSuccesCount = 0;
        m_connectFalseCount = 0;
        //启动统计数据计时器
        if(m_timer1 != NULL){
            delete m_timer1;
        }
        m_timer1 = new QTimer(this);
        connect(m_timer1,SIGNAL(timeout()),this,SLOT(onTimer1Out()));
        m_timer1->setInterval(6000);
        m_timer1->start();


        for(int i = 0;i < appendCount;++i){
            mytcpprogress* pro = new mytcpprogress;
            QThread* thr = new QThread;
            pro->moveToThread(thr);
            thr->start();
            m_progressList.append(pro);
            m_threadList.append(thr);
            m_progressStatueList.append(false);

            connect(this,SIGNAL(newTcpServiceProgress(QString,int,int)),pro,SLOT(onNewTcpServiceProgress(QString,int,int)));
            emit newTcpServiceProgress(m_serverAddress,m_serverPort,m_progressList.count() - 1);
            disconnect(this,SIGNAL(newTcpServiceProgress(QString,int,int)),pro,SLOT(onNewTcpServiceProgress(QString,int,int)));

            connect(pro,SIGNAL(connected(QString,int)),this,SLOT(onProgressConnect(QString,int)));
            connect(pro,SIGNAL(disconnected(QString,int)),this,SLOT(onProgressDisonnect(QString,int)));
            connect(this,SIGNAL(sendMessage(QByteArray,int)),pro,SLOT(on_message_send(QByteArray,int)));
            connect(pro,SIGNAL(newMessage(QByteArray,int)),this,SLOT(on_progress_newMessage(QByteArray,int)));
            //            connect(this,SIGNAL(gotoDisconnect(int)),pro,SLOT(onGotoDisconnect(int)));
        }

        ui->actSetServerMain->setEnabled(false);
    }
}


void myServerTest::on_actSetMaxCount_triggered()
{
    bool ok = false;
    int newCount = QInputDialog::getInt(0,tr("设置最大连接数量"),tr("请输入:"),m_maxCount,0,1000,100,&ok);
    if(ok == true){//如果输入合理

        if(newCount >= m_progressList.count()){//如果输入值大于当前线程数量,则同意修改
            m_maxCount = newCount;

        }else{//如果输入值小于当前线程数量,则拒绝修改
            QMessageBox::warning(0,tr("警告"),tr("修改失败,输入不能小于当前线程数量."));
            return;
        }

    }
}

void myServerTest::onProgressConnect(QString add, int index)
{
    Q_UNUSED(add);
    m_progressStatueList.removeAt(index);//如果某个线程连接成功就修改对应的状态值
    m_progressStatueList.insert(index,true);
    ++m_connectSuccesCount;
    if(m_connectFalseCount + m_connectSuccesCount == m_connectTotalCount && m_timer1->isActive()){//如果提前结束所有连接尝试
        onTimer1Out();//触发响应函数
    }

    m_statueLabel3.setText(tr("活跃连接:")+QString::asprintf("%d",currentActiveConnectCount()));//更新状态栏活跃连接显示
}

void myServerTest::onProgressDisonnect(QString add, int index)
{
    Q_UNUSED(add);
    m_progressStatueList.removeAt(index);//如果某个线程连接断开就修改对应的状态值
    m_progressStatueList.insert(index,false);


    ++m_connectFalseCount;
    if(m_connectFalseCount + m_connectSuccesCount == m_connectTotalCount && m_timer1->isActive()){//如果提前结束所有连接尝试
        onTimer1Out();//触发响应函数
    }

    //释放线程程序资源
    m_progressList.at(index)->deleteLater();

    m_threadList.at(index)->quit();
    m_threadList.at(index)->wait();

    m_progressList.removeAt(index);
    mytcpprogress* p = NULL;
    m_progressList.insert(index,p);

    m_threadList.at(index)->deleteLater();
    m_threadList.removeAt(index);
    QThread* t = NULL;
    m_threadList.insert(index,t);

    if(currentActiveConnectCount() == 0){//如果当前已经没有活跃的连接了
        m_progressList.clear();
        m_threadList.clear();
        m_progressStatueList.clear();
        ui->actSetServerMain->setEnabled(true);
    }

    m_statueLabel3.setText(tr("活跃连接:")+QString::asprintf("%d",currentActiveConnectCount()));//更新状态栏活跃连接显示
}

void myServerTest::on_progress_newMessage(QByteArray recData, int index)
{

}

void myServerTest::onTimer1Out()
{
    m_timer1->stop();
    ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+tr("尝试连接总数:")+QString::asprintf("%d",m_connectTotalCount)+" 成功:"+QString::asprintf("%d",m_connectSuccesCount)+" 失败:"+QString::asprintf("%d",m_connectFalseCount));

    m_connectSuccesCount = 0;
    m_connectFalseCount = 0;
    ui->actAppendMain->setEnabled(true);


}

void myServerTest::closeEvent(QCloseEvent *e)
{
    for(int i = m_progressList.count() - 1;i >= 0; --i){
        if(m_progressList.at(i) != NULL){

            //            emit gotoDisconnect(i);
            m_progressList.at(i)->deleteLater();

            m_threadList.at(i)->quit();
            m_threadList.at(i)->wait();

            //            delete m_progressList.at(i);

            m_threadList.at(i)->deleteLater();

        }
    }

    e->accept();
}


void myServerTest::on_actDeleteMain_triggered()
{
    bool ok = false;
    int deleteCount = QInputDialog::getInt(0,tr("断开连接"),tr("请输入要断开的连接数量:"),0,0,currentActiveConnectCount(),10,&ok);
    if(ok == true){//如果输入合理
        if(deleteCount == 0){
            return;
        }

        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+tr("正在统计数据..."));
        ui->actDeleteMain->setEnabled(false);

        //执行断开连接操作
        int endIndex = m_progressStatueList.count() - 1;
        for(int i = 0;i < deleteCount; --endIndex){

            if(m_progressStatueList.at(endIndex) == false){//如果当前索引的连接已经断开则不计数
                continue;
            }else{//执行释放资源操作

                //                emit gotoDisconnect(endIndex);
                m_progressList.at(endIndex)->deleteLater();

                m_threadList.at(endIndex)->quit();
                m_threadList.at(endIndex)->wait();

                //    delete m_progressList.at(index);
                m_progressList.removeAt(endIndex);
                mytcpprogress* p = NULL;
                m_progressList.insert(endIndex,p);

                m_threadList.at(endIndex)->deleteLater();
                m_threadList.removeAt(endIndex);
                QThread* t = NULL;
                m_threadList.insert(endIndex,t);

                m_progressStatueList.removeAt(endIndex);
                m_progressStatueList.insert(endIndex,false);

                ++i;
            }

        }

        if(currentActiveConnectCount() == 0){//如果当前已经没有活跃的连接了
            m_progressList.clear();
            m_threadList.clear();
            m_progressStatueList.clear();
            ui->actSetServerMain->setEnabled(true);
        }

        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+"操作成功,当前活跃连接数:"+QString::asprintf("%d",currentActiveConnectCount()));
        ui->actDeleteMain->setEnabled(true);
        m_statueLabel3.setText(tr("活跃连接:")+QString::asprintf("%d",currentActiveConnectCount()));//更新状态栏活跃连接显示
    }

}


void myServerTest::on_actDeleteAllMain_triggered()
{

    int result = QMessageBox::information(0,tr("确认操作"),tr("确定断开所有连接?"),QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Cancel);
    if(result != QMessageBox::Ok){//如果用户取消操作
        return;
    }

    if(currentActiveConnectCount() == 0){//如果当前没有活跃的连接
        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+tr("当前没有活跃的连接."));
        return;
    }


    ui->actDeleteAllMain->setEnabled(false);

    //执行断开连接操作

    for(int i = 0;i < m_progressStatueList.count(); ++i){

        //执行释放资源操作
        if(m_progressStatueList.at(i) == true){
            m_progressList.at(i)->deleteLater();

            m_threadList.at(i)->quit();
            m_threadList.at(i)->wait();

            //    delete m_progressList.at(index);
            m_progressList.removeAt(i);
            mytcpprogress* p = NULL;
            m_progressList.insert(i,p);

            m_threadList.at(i)->deleteLater();
            m_threadList.removeAt(i);
            QThread* t = NULL;
            m_threadList.insert(i,t);

            m_progressStatueList.removeAt(i);
            m_progressStatueList.insert(i,false);


        }

    }

    m_progressList.clear();
    m_threadList.clear();
    m_progressStatueList.clear();
    ui->actSetServerMain->setEnabled(true);

    ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [系统] ")+"已关闭所有连接.");
    ui->actDeleteAllMain->setEnabled(true);
    m_statueLabel3.setText(tr("活跃连接:")+QString::asprintf("%d",currentActiveConnectCount()));//更新状态栏活跃连接显示

}


void myServerTest::on_actQuitMain_triggered()
{
    this->close();
}


void myServerTest::on_actSendMessageMain_triggered()
{
    if(currentActiveConnectCount() == 0){//如果当前没有活跃的连接
        QMessageBox::information(0,tr("提示"),tr("当前没有活跃的连接!"));
        return;
    }

    bool ok = false;
    QString str = QInputDialog::getText(0,tr("发送信息"),tr("请输入要发送的信息:"),QLineEdit::Normal,"",&ok);
    if(ok == true){//如果输入完成
        QByteArray byAr = str.toUtf8();
        for(int i = 0;i < m_progressStatueList.count(); ++i){
            if(m_progressStatueList.at(i) == true){//如果当前连接为活跃状态
                emit sendMessage(byAr,i);

            }
        }
        ui->txtLogMain->append(QTime::currentTime().toString("hh:mm:ss")+tr(" [发送] ")+str);

    }
}

